<template>
  <div class="goods-add">
    <van-sticky>
      <van-nav-bar :title="$route.meta.title" left-arrow @click-left="onClickLeft" style="width: 100%" />
    </van-sticky>
    <van-form @submit="onSubmit">
      <van-cell-group class="goods-add-items">
        <van-field label="商品视频" input-align="right" accept="image/mp4" readonly center class="video-name">
          <template #right-icon>
            <van-uploader v-model="pdata.menuvideo" accept="video/*" :after-read="videoUrl" multiple :max-count="1" @oversize="videosize" :max-size="10240 * 1024">
              <!-- 封面插槽 -->
              <template #preview-cover>
                <van-image :src="require('@/assets/player.png')" width="100%" height="100%" fit="cover" class="preview-img" />
              </template>
            </van-uploader>
          </template>
        </van-field>
        <van-field label="商品图片" input-align="right" readonly center>
          <template #right-icon>
            <van-uploader v-model="pdata.image" :after-read="afterRead" :max-count="5" accept="image/*" @oversize="onOversize" :max-size="5120 * 1024" />
          </template>
        </van-field>
        <van-field :rules="[{ required: true}]" label="商品名称" v-model="pdata.name" placeholder="请输入商品名称" input-align="right" />
        <van-field :rules="[{ required: true}]" label="商品类型" v-model="pdata.type" :value="pdata.type" placeholder="请选择类型" @click="picker('l')" readonly input-align="right" is-link />
        <van-field :rules="[{ required: true}]" label="商品价格" type="number" v-model="pdata.price" placeholder="请输入商品价格" input-align="right">
          <template #extra><span style="margin-left: 5px">元</span></template>
        </van-field>
        <van-field :rules="[{ required: true}]" label="商品重量" type="number" v-model="pdata.weights" placeholder="请输入商品重量" input-align="right">
          <template #extra><span style="margin-left: 5px">Kg</span></template>
        </van-field>
        <van-field :rules="[{ required: true}]" label="商品主料" type="textarea" autosize v-model="pdata.sidedish" placeholder="请输入商品主料" input-align="right" />
        <van-field :rules="[{ required: true}]" label="商品描述" type="textarea" autosize v-model="pdata.desc" placeholder="请输入商品描述" input-align="right" />
        <div class="spacing"></div>
        <van-field label="是否特价" input-align="right">
          <template #input>
            <van-radio-group v-model="pdata.discount" checked-color="#1bb89c" direction="horizontal">
              <van-radio name="0">否</van-radio>
              <van-radio name="1">是</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field label="特价价格" v-model="pdata.sprice" type="number" v-if="pdata.discount == '1'" placeholder="请输入特价价格" input-align="right">
          <template #extra><span style="margin-left: 5px">元</span></template>
        </van-field>
        <div class="spacing"></div>
        <van-field :rules="[{ required: true}]" label="库存" v-model="pdata.stock" type="number" placeholder="请输入库存" input-align="right" />
        <van-field :rules="[{ required: true}]" label="生产日期" v-model="pdata.date1" placeholder="请选择时间" readonly input-align="right" @click="picker('s')" is-link />
        <van-field :rules="[{ required: true}]" label="保质期" v-model="pdata.date2" placeholder="请选择时间" readonly input-align="right" @click="picker('b')" is-link />
        <van-field :rules="[{ required: true}]" label="优先级" type="number" v-model="pdata.sort" placeholder="请输入商品类型优先级，如：1、2" input-align="right" />
      </van-cell-group>
      <div class="goods-add-set">
        <div class="set-center">
          <van-button round type="info" color="#1bb89c">新 增</van-button>
        </div>
      </div>
    </van-form>
    <!-- 商品类型 -->
    <van-popup v-model="showtype" round position="bottom" :style="{ height: '50%' }">
      <van-picker :columns="typeList" show-toolbar title="选择类型" @confirm="confirm1" @cancel="showtype=false" />
    </van-popup>
    <!-- 生产日期 -->
    <van-popup v-model="date_start" round position="bottom" :style="{ height: '50%' }">
      <van-datetime-picker v-model="currentDate" type="date" title="选择日期" :formatter="formatter" :min-date="minDate" :max-date="maxDate" @confirm="confirm" @cancel="date_start=false" />
    </van-popup>
    <!-- 保质期 -->
    <van-popup v-model="timeshow" round position="bottom" :style="{ height: '50%' }">
      <van-datetime-picker v-model="lifespan" type="date" title="选择日期" :formatter="formatter" :min-date="minDate1" :max-date="maxDate1" @confirm="confirm2" @cancel="timeshow=false" />
    </van-popup>
  </div>
</template>

<script>
import { Toast } from "vant";
export default {
  name: "GoodsAdd",
  data () {
    return {
      showtype: false,
      timeshow: false,
      date_start: false,
      currentDate: new Date(), // 生产日期
      minDate: new Date(1970, 0, 1), // 生产日期最小日期
      maxDate: new Date(3025, 12, 31), // 生产日期最大日期
      lifespan: new Date(new Date().getTime() + 86400000 * 1), // 保质期
      minDate1: new Date(1970, 0, 1), // 保质期最小日期
      maxDate1: new Date(3025, 12, 31), // 保质期最大日期
      disabled: false,
      typeList: [],
      imageurl: [],
      videourl: '',
      type: "",
      pdata: {
        menuvideo: [],
        image: [],
        name: "",
        type: "",
        price: "",
        weights: "",
        desc: "",
        sidedish: "",
        discount: "0",
        sprice: "",
        stock: "",
        date1: "",
        date2: "",
        sort: "",
      },
      typeid: "",
    };
  },
  created () {
    this.typelists();
  },
  methods: {
    onClickLeft () {
      this.$router.push({ name: "goods" })
    },
    // 图片限制
    onOversize () {
      Toast.fail("图片大小不能超过5M");
    },
    // 视频限制
    videosize () {
      Toast.fail("视频大小不能超过10M");
    },
    picker (type) {
      this.type = type;
      if (type == "s") {
        this.date_start = true;
      } else if (type == "b") {
        this.timeshow = true;
      } else {
        this.showtype = true;
      }
    },
    formatter (type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      }
      return value;
    },
    checktime (v) {
      if (v < 10) {
        v = "0" + v;
      }
      return v;
    },
    typelists () {
      this.$axios("/products/prodtypelist", {
        type: 1,
      })
        .then((res) => {
          this.typeList = res.data.data.map((v) => {
            return {
              text: v.type_name,
              id: v.id,
            };
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 生产日期
    confirm (e) {
      var y = e.getFullYear();
      var m = this.checktime(e.getMonth() + 1);
      var d = this.checktime(e.getDate());
      var dates = y + "-" + m + "-" + d;
      this.pdata.date1 = dates;
      this.date_start = false;
    },
    // 商品类型
    confirm1 (val) {
      this.pdata.type = val.text;
      this.typeid = val.id;
      this.showtype = false;
    },
    // 保质期
    confirm2 (e) {
      var y = e.getFullYear();
      var m = this.checktime(e.getMonth() + 1);
      var d = this.checktime(e.getDate());
      var dates = y + "-" + m + "-" + d;
      if (Date.parse(this.pdata.date1) >= Date.parse(dates)) {
        Toast.fail('保质期必须大于生产日期')
      } else if (this.pdata.date1 === "") {
        Toast.fail('生产日期不能为空')
      } else {
        this.pdata.date2 = dates;
        this.timeshow = false;
      }
    },
    // 图片上传
    afterRead (file) {
      let params = new FormData();
      params.append("file", file.file);
      this.$notoken("/main/upload", params)
        .then((res) => {
          let res_url = res.data.data
          this.imageurl.push(res_url)
        });
    },
    // 视频上传
    videoUrl (file) {
      let params = new FormData();
      params.append("file", file.file);
      this.$notoken("/main/upload", params)
        .then((res) => {
          this.videourl = res.data.data
        });
    },
    onSubmit () {
      this.$axios("/products/createproducts", {
        menuvideo: this.videourl, //产品视频
        menuimage: this.imageurl, //产品图片
        type: this.typeid, //产品类型
        name: this.pdata.name, //产品名称
        sidedish: this.pdata.sidedish, //产品主料
        remark: this.pdata.desc, //产品描述
        price: this.pdata.price, //价格
        issprice: this.pdata.discount, //是否有特价
        sprice: this.pdata.sprice, //特价价格
        stocknum: this.pdata.stock, //产品库存量
        manufacturedate: this.pdata.date1, //产品生产日期
        qualityperiod: this.pdata.date2, //产品保质期到期  日期
        sort: this.pdata.sort, //排序
        weight: this.pdata.weights, //重量（公斤）
      })
        .then((res) => {
          if (res.data.code == 1) {
            Toast.loading("添加成功");
            setTimeout(() => {
              Toast.success("添加成功");
              this.$router.go(-1);
            }, 1000);
          } else {
            Toast.fail("添加失败");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>
<style lang="less" scoped>
.goods-add {
  display: flex;
  flex-direction: column;
  &-items {
    width: 100%;
    .video-name {
      /deep/ .van-uploader__file-name {
        display: none;
      }
      .preview-img {
        /deep/ .van-image__img {
          border-radius: 15px;
        }
      }
    }
    &-img {
      /deep/ .van-image__img {
        width: 120px;
        height: 120px;
        border-radius: 10px;
      }
    }
    /deep/ .van-field__label {
      color: black;
    }
    /deep/ .van-uploader__file,
    /deep/ .van-uploader__upload,
    /deep/ .van-uploader__preview,
    /deep/ .van-uploader__preview-image {
      border-radius: 15px;
      width: 1.1rem;
      height: 1.1rem;
    }
    .spacing {
      width: 100%;
      height: 20px;
      background-color: #f5f5f5;
    }
  }
  &-set {
    display: flex;
    flex-direction: column;
    width: 100%;
    margin: 100px auto;
    .set-center {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 100%;
      margin: 0 auto;
      .set-spacing {
        height: 30px;
      }
      /deep/ .van-button {
        width: 80%;
        height: 80px;
        font-weight: bold;
        font-size: 30px;
      }
    }
  }
}
</style>